package org.ayachinene.leetcode.problems;

import java.util.*;

public class P1604 {

    static class Solution {

        private static final int HOUR = 0;
        private static final int MIN = 1;

        public List<String> alertNames(String[] keyName, String[] keyTime) {
            int size = keyName.length;

            Map<String, List<String>> timesMap = new HashMap<>();
            for (int i = 0; i < size; i++) {
                timesMap.putIfAbsent(keyName[i], new ArrayList<>());
                timesMap.get(keyName[i]).add(keyTime[i]);
            }

            List<String> res = new ArrayList<>();
            timesMap.forEach((name, times) -> {
                if (times.size() < 3) {
                    return;
                }

                times.sort(Solution::compareTime);
                for (int i = 0; i <= times.size() - 3; i++) {
                    String t1 = times.get(i);
                    String t2 = times.get(i + 1);
                    String t3 = times.get(i + 2);

                    int interval = getIntervalInMin(t1, t2) + getIntervalInMin(t2, t3);
                    if (interval <= 60) {
                        res.add(name);
                        break;
                    }
                }
            });

            Collections.sort(res);
            return res;
        }

        private static int compareTime(String t1, String t2) {
            return compareTime(convert(t1), convert(t2));
        }

        private static int compareTime(int[] t1, int[] t2) {
            if (t1[HOUR] < t2[HOUR]) {
                return -1;
            } else if (t1[HOUR] == t2[HOUR]) {
                return Integer.compare(t1[MIN], t2[MIN]);
            } else {
                return 1;
            }
        }

        private static int getIntervalInMin(String t1, String t2) {
            return getIntervalInMin(convert(t1), convert(t2));
        }

        private static int getIntervalInMin(int[] t1, int[] t2) {
            // Assert that t2 is later than t1.
            int hourInterval = t2[HOUR] - t1[HOUR];
            int minInterval = t2[MIN] - t1[MIN];
            return hourInterval * 60 + minInterval;
        }

        private static int[] convert(String time) {
            String[] s = time.split(":");
            return new int[] { Integer.parseInt(s[0]), Integer.parseInt(s[1]) };
        }
    }
}
